package com.jeff.game.tools.level;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

/**
 * A mapping of characters that will appear in a block file to an actual image
 */
public class BlockMap
{
  private final BufferedImage image;

  private final int cols;
  private final int blockWidth;
  private final int blockHeight;

  private final Map<Character, Integer> mapping;
  private final Map<Character, BufferedImage> imageCache = new HashMap<Character, BufferedImage>();

  /**
   * @param filename File which holds block images
   * @param rows Number of rows in file
   * @param cols Number of columns in file
   * @param mapping A character to index mapping for blocks
   * @throws IOException
   */
  public BlockMap(
      String filename, int rows, int cols, Map<Character, Integer> mapping)
      throws IOException
  {
    image = ImageIO.read(new File(filename));

    this.cols = cols;
    this.blockWidth = image.getWidth() / cols;
    this.blockHeight = image.getHeight() / rows;

    this.mapping = mapping;
  }

  /**
   * Get the image for a particular block
   * @param symbol Character representing block
   * @return The block's image
   */
  public Image getImage(char symbol)
  {
    if (imageCache.get(symbol) == null)
    {
      int index = mapping.get(symbol);
      int x = (index % cols) * blockWidth;
      int y = (index / cols) * blockHeight;

      imageCache.put(symbol, image.getSubimage(x, y, blockWidth, blockHeight));
    }

    return imageCache.get(symbol);
  }
}
